﻿Imports System.Data

Partial Class WebForm_ManageDownload_ManageFile
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Button1)
    End Sub

    '按下刪除 
    Protected Sub lbtnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Try

            Dim sql As New MyStringBuilder
            Dim dat As New clsData

            sql.AppendFormat("SELECT * ")
            sql.AppendFormat("FROM UploadFiles ")
            sql.AppendFormat("WHERE FileSaveName='{0}' ", GridView1.DataKeys(DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow).RowIndex).Value)

            Dim tmpTable As DataTable = dat.GetData(sql)

            If tmpTable IsNot Nothing AndAlso tmpTable.Rows.Count > 0 Then

                Dim objDataRow As DataRow = tmpTable.Rows(0)

                '刪除檔案 
                Dim FileInfo As New System.IO.FileInfo((Server.MapPath(objDataRow("FileSavePath").ToString()) + objDataRow("FileSaveName").ToString() & ".") + objDataRow("FileType").ToString())
                If FileInfo.Exists Then
                    FileInfo.Delete()
                End If

                'ObjectDataSource1.DeleteParameters("Guid").DefaultValue = objDataRow("FileSavePath")
                ObjectDataSource1.Delete()

            End If

        Catch ex As Exception
            MyObj.WriteLog(ex.Message)
            'MyObj.ShowMessage(Me.GetLocalResourceObject("DelateFail"))
        End Try

    End Sub

    '下載檔案 
    Protected Sub lbtnDownLoadFile_Click(ByVal sender As Object, ByVal e As EventArgs)

        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("SELECT * ")
        sql.AppendFormat("FROM UploadFiles ")
        sql.AppendFormat("WHERE FileSaveName='{0}' ", GridView1.DataKeys(DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow).RowIndex).Value)

        Dim tmpTable As DataTable = dat.GetData(sql)

        If tmpTable IsNot Nothing AndAlso tmpTable.Rows.Count > 0 Then

            Dim objDataRow As DataRow = tmpTable.Rows(0)

            Dim FileInfo As New System.IO.FileInfo((Server.MapPath(objDataRow("FileSavePath").ToString()) + objDataRow("FileSaveName").ToString() & ".") + objDataRow("FileType").ToString())

            If FileInfo.Exists Then
                Me.Response.Clear()
                Me.Response.AddHeader("Content-Disposition", ("attachment;filename=" & objDataRow("FileName")))
                Me.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("big5")
                Me.Response.AddHeader("Content-Length", FileInfo.Length.ToString())
                Me.Response.ContentType = "application/octet-stream"
                Me.Response.WriteFile(FileInfo.FullName)

                Me.Response.End()

            End If

        End If

    End Sub

    Private Sub SaveUploadFile(ByVal theClass As String, ByVal theType As String, ByVal theFileUpload As FileUpload, ByVal theDesc As String)
        If Not theFileUpload.HasFile Then
            MyObj.ShowMessage(Me.GetLocalResourceObject("FileFail"))
            Exit Sub
        End If

        Dim strFileLongName As String = theFileUpload.PostedFile.FileName
        Dim strFileName As String = strFileLongName.Substring(strFileLongName.LastIndexOf("\") + 1)
        Dim strFileType As String = strFileName.Substring(strFileName.LastIndexOf(".") + 1)
        Dim strFileShortName As String = strFileName.Substring(0, strFileName.LastIndexOf("."))
        Dim strFileSize As String = theFileUpload.PostedFile.ContentLength.ToString()

        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("SELECT FilePath ")
        sql.AppendFormat("FROM FileGroup ")
        sql.AppendFormat("WHERE FileGroupID='{0}' ", strClass)

        Dim tmpTable As DataTable = dat.GetData(sql)

        If tmpTable IsNot Nothing AndAlso tmpTable.Rows.Count > 0 Then

            Dim strFileSavePath As String = tmpTable.Rows(0).Item("FilePath")
            Dim guidFileSaveName As Guid = Guid.NewGuid()
            Dim strFileSaveLongName As String = (Server.MapPath(strFileSavePath) + guidFileSaveName.ToString() & ".") + strFileType

            Try
                '將檔案上傳至server 
                theFileUpload.PostedFile.SaveAs(strFileSaveLongName)
                '將檔案上傳至DataTable 
                ObjectDataSource1.InsertParameters("theClass").DefaultValue = theClass
                ObjectDataSource1.InsertParameters("theType").DefaultValue = theType
                ObjectDataSource1.InsertParameters("FileName").DefaultValue = strFileName
                ObjectDataSource1.InsertParameters("FileShortName").DefaultValue = strFileShortName
                ObjectDataSource1.InsertParameters("FileType").DefaultValue = strFileType
                ObjectDataSource1.InsertParameters("FileSavePath").DefaultValue = strFileSavePath
                ObjectDataSource1.InsertParameters("FileSaveName").DefaultValue = guidFileSaveName.ToString()
                ObjectDataSource1.InsertParameters("FileDesc").DefaultValue = txtDesc.Text
                ObjectDataSource1.InsertParameters("CreateBy").DefaultValue = Page.User.Identity.Name
                ObjectDataSource1.InsertParameters("RoleID").DefaultValue = ddlDefaultRole.SelectedValue
                ObjectDataSource1.InsertParameters("CanRead").DefaultValue = True
                ObjectDataSource1.InsertParameters("CanDelete").DefaultValue = True

                ObjectDataSource1.Insert()

            Catch ex As Exception
                If System.IO.File.Exists(strFileSaveLongName) Then
                    System.IO.File.Delete(strFileSaveLongName)
                End If
                MyObj.ShowMessage(Me.GetLocalResourceObject("FileFail"))
            End Try

        End If


    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        '按下新增 
        SaveUploadFile(strClass, strType, hiFileUpload, txtDesc.Text)
        txtDesc.Text = ""
    End Sub

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then
            ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(TryCast(e.Row.FindControl("lbtnDownLoadFile"), LinkButton))
        End If

    End Sub

    Public Event MySelectedIndexChanged(ByVal source As Object, ByVal e As EventArgs)

    Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged
        RaiseEvent MySelectedIndexChanged(Me, New EventArgs)
    End Sub

End Class


Partial Class WebForm_ManageDownload_ManageFile

    Public Sub InitDataAndShow()

        strClass = "PublicDownload"
        isEdit = True

        Me.txtDesc.Text = String.Empty

        If Not isEdit Then

            hiFileUpload.Enabled = False
            Button1.Enabled = False
            txtDesc.Enabled = False
            GridView1.Columns(0).Visible = False

        End If

        SqlDataSource1.SelectParameters("UserID").DefaultValue = Page.User.Identity.Name

        ObjectDataSource1.SelectParameters("theClass").DefaultValue = strClass
        ObjectDataSource1.SelectParameters("theType").DefaultValue = strType
        ObjectDataSource1.SelectParameters("LoginUser").DefaultValue = Page.User.Identity.Name

        GridView1.DataSourceID = ObjectDataSource1.ID
        GridView1.DataBind()

    End Sub


#Region "Property"

    Public Property strClass() As String
        Get
            Return DirectCast(ViewState("strClass"), String)
        End Get
        Set(ByVal value As String)

            ViewState("strClass") = value
        End Set
    End Property

    Public Property strType() As String
        Get
            Return DirectCast(ViewState("strType"), String)
        End Get
        Set(ByVal value As String)

            ViewState("strType") = value
        End Set
    End Property

    Public Property isEdit() As Boolean
        Get
            Return CBool(ViewState("isEdit"))
        End Get
        Set(ByVal value As Boolean)

            ViewState("isEdit") = value
        End Set
    End Property

    Public ReadOnly Property SelectedFileSaveName() As Guid

        Get
            Return Me.GridView1.SelectedValue
        End Get

    End Property

#End Region

End Class
